#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#include<iostream>
#include<sstream>
#include<deque>
#include <queue>
#define MOD 1000000007
class Solution {
public:
    int maximumInvitations(std::vector<int>& favorite) {
        int n = favorite.size();
        std::vector<int> du(n,0);
        for (int i = 0; i < n; i++)
        {
            du[favorite[i]]++;
        }
        std::queue<int> q;
        for (int i = 0;i<n ;i++)
        {
            if (du[i]==0)
            {
                q.push(i);
            }
        }
        std::vector<int> deep(n,0);
        while (!q.empty())
        {
            int index  = q.front();
            q.pop(); 
            deep[favorite[index]] = std::max(deep[favorite[index]],deep[index]+1);
            du[favorite[index]]--;
            if (du[favorite[index]] == 0)
            {
                q.push(favorite[index]);
            }
        }
        int bigringsize =0;
        int smallringsize=0 ;
        for (int i=0; i<n; i++)
        {
            if (du [i]!=0)
            {
                int next=favorite[i];
                du[i] =0;
                int size =1;
                while (du[next]!=0)
                {
                    du[next]=0;
                    size++;
                    next=favorite[next];
                }
                if (size == 2)
                {
                    smallringsize+=size+ deep[i]+deep[favorite[i]];
                }else
                {
                    bigringsize = std::max(bigringsize,size);
                }
            }
        }
        return std::max(bigringsize,smallringsize);
    }
};
